package org.onvivals.app.ai.tts.model.reecho;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import org.onvivals.app.ai.tts.AbstractTtsService;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ReechoTtsService
 *
 * @author weirdor (179946422@qq.com)
 * @version v1.0.0
 */
@Slf4j
public class ReechoTtsService extends AbstractTtsService {

	private JSONObject ttsConfig;


	private static final Lock lock = new ReentrantLock();

	public ReechoTtsService(JSONObject config) {
		this.ttsConfig = config;
	}

	public ReechoTtsService() {
	}

	public static String generateFilePath() {
		lock.lock();
		try {
			String tmpDir = System.getProperty("java.io.tmpdir");
			String uniqueId = IdUtil.getSnowflakeNextIdStr();
			return tmpDir + uniqueId + ".mp3";
		} finally {
			lock.unlock();
		}
	}

	/**
	 * 文字转换语音
	 *
	 * @param content 转换的文字
	 * @return Optional<String> 文件路径
	 */
	@Override
	public Optional<String> speechSynthesizer(String id, String content) {
//		ReechoConfig reechoConfig = JSONUtil.toBean(sttConfig.getTtsConfig().toJSONString(),ReechoConfig.class);
		String key = ttsConfig.getStr("key");
		String voiceId = ttsConfig.getStr("voice_id");
		Map<String, Object> paramMap = MapUtil.newHashMap();
		paramMap.put("voiceId", voiceId);
		paramMap.put("text", content);
		paramMap.put("flash", true);
		paramMap.put("stream", false);
		JSONObject jsonObject = new JSONObject(paramMap);
		HttpResponse response = HttpUtil.createPost("https://v1.reecho.cn/api/tts/simple-generate")
				.header("Authorization", "Bearer " + key)
				.body(jsonObject.toString())
				.execute();
		if (response.isOk()) {
			JSONObject result = new JSONObject(response.body());
			String data = result.getJSONObject("data").getStr("audio");
			return Optional.of(data);
		} else {
			log.error("ReechoTtsService error: {}", response.body());
			return Optional.empty();
		}
	}
}
